﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using SharedCongkak;

using Path = SharedCongkak.Path;
namespace Congkak
{
    public class EditState: GameState
    {
        private AbstractHole selectedHole;
        private AbstractHole sourceHole;

        public EditState(GameplayScreen gamePlay)
            : base(gamePlay)
        {
            level.OnHoleSelect += HoleSelected;
        }

        public override void HandleInput(InputState input, PlayerIndex? ControllingPlayer)
        {
            InputState.MouseButton button;
            int mouseX, mouseY;
            if (input.IsMouseMoved(out mouseX, out mouseY))
            {
                if (selectedHole != null)
                {
                    selectedHole.Center = new Vector2(mouseX, mouseY);
                }
                if (sourceHole != null)
                {
                    level.Hover(mouseX, mouseY);
                }

            }

            if (input.IsMousePressed(out button, out mouseX, out mouseY))
            {
                AbstractHole hole = level.GetHole(new Point(mouseX, mouseY));
                if (hole != null)
                {
                    if (button == InputState.MouseButton.Left)
                    {
                        selectedHole = level.GetHole(new Point(mouseX, mouseY));
                        level.HighlightHole(selectedHole, null);
                    }
                    else if (button == InputState.MouseButton.Right)
                    {
                        sourceHole = level.GetHole(new Point(mouseX, mouseY));
                        level.HighlightHole(sourceHole, null);
                    }
                }
            }

            if (input.IsMouseReleased(out button, out mouseX, out mouseY))
            {
                
                AbstractHole hole = level.GetHole(new Point(mouseX, mouseY));
                if (sourceHole != null && hole != null)
                {
                    if (sourceHole == hole)
                        level.RemovePath(sourceHole.NextEdges.Last<Path>());
                    else
                        level.AddPath(sourceHole, hole);
                }
                sourceHole = null;
                selectedHole = null;
            }

            if (input.IsMouseClicked(InputState.MouseButton.Middle, out mouseX, out mouseY))
            {
                gamePlay.ChangeGameState(new PickState(gamePlay));
            }


            
        }

        public void HoleSelected(object hole, EventArgs eventArgs)
        {

        }

        public override void Update(GameTime gameTime)
        {


        }

        

    }
}
